import AuthAPI from "@/api/auth";
import UserAPI from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/model";
import { UserInfo } from "@/api/user/model";
import { TOKEN_KEY } from "@/enums/CacheEnum";

export const useUserStore = defineStore("user", () => {
  const user = ref<any>({
    roles: [],
    perms: [],
  });

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data) => {
          const { token } = data;
          localStorage.setItem(TOKEN_KEY, token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<any>((resolve, reject) => {
      // const datad: UserInfo = {
      //   userId: 1,
      //   username: "test",
      //   nickname: "string",
      //   avatar: "test",
      //   roles: ["ROOT"],
      //   perms: [],
      // };
      // Object.assign(user.value, { ...datad });
      // resolve(datad);
      UserAPI.getInfo().then((data) => {
        console.log(data);
        data.roles = ["ROOT"];
        data.perms = [];
        Object.assign(user.value, { ...data });
        const datad: UserInfo = {
          userId: data.gridId,
          username: data.gname,
          nickname: data.gname,
          avatar: "",
          roles: ["ROOT"],
          perms: [],
        };
        resolve(datad);
      });
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      localStorage.setItem(TOKEN_KEY, "");
      location.reload(); // 清空路由
      resolve();
      // AuthAPI.logout()
      //   .then(() => {
      //     localStorage.setItem(TOKEN_KEY, "");
      //     location.reload(); // 清空路由
      //     resolve();
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });
    });
  }

  // remove token
  function resetToken() {
    console.log("resetToken");
    return new Promise<void>((resolve) => {
      localStorage.setItem(TOKEN_KEY, "");
      resetRouter();
      resolve();
    });
  }

  return {
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
